package example.designpattern.fsm.transition;


import example.designpattern.fsm.StateContext;
import example.designpattern.fsm.listener.TransitionListener;
import example.designpattern.fsm.state.AbstractState;
import java.util.List;

/**
 * 状态转换过程类
 */
public class StateTransition {
  protected AbstractState previousState;
  protected AbstractState nextState;
  protected TransitionFunction transitionFunction;

  public StateTransition(StateTransitionBuilder builder) {
    this.previousState = builder.getPreviousState();
    this.nextState = builder.getNextState();
    this.transitionFunction = builder.getTransitionFunction();
  }

  public boolean support(AbstractState previousState) {
    return this.previousState.equals(previousState);
  }

  public void transition(StateContext context) {
    if (!support(context.getCurrentState())) {
      return;
    }
    notifyTransitionListener(context);
    boolean transition = transitionFunction.transition(this.previousState, this.nextState, context);
    if (transition) {
      context.updateState(nextState);
    }
  }

  public void notifyTransitionListener(StateContext context) {
    List<TransitionListener> transitionListeners = context.getTransitionListeners();
    for (TransitionListener transitionListener : transitionListeners) {
      transitionListener.onTransition(this.previousState, this.nextState);
    }
  }

}